<template>
<div>
<!-- 操作按钮区域 -->
    <div class="table-operator">
        <a-button type="primary" icon="folder-add" @click="folderVisible=true">新建文件夹</a-button>
        <a-button type="primary" icon="cloud-upload" @click="clickUpload">上传文件</a-button>
    </div>

<!-- 文件信息列表 -->
  <a-table :columns="columns" :data-source="fileList" :pagination="false">
    <span slot="name" slot-scope="text,record">
      <a @click="fileDetail(record.type,record.path,record.id)">
        <img :src="chooseIcon(record.type,record.path)" style="width: 28px; height: 28px; margin-right: 8px" />
        <span >  {{record.name}}</span>
      </a>
    </span>
    <span slot="customTitle"><a-icon type="left" style="color: skyblue; font-size: medium;" @click="reback()" /> 文件名</span>
        <!-- 操作 -->
    <template slot="operation" slot-scope="text, record">
    <a-popconfirm
      v-if="fileList.length"
      title="Sure to delete?"
      @confirm="onDeleteFile(record.id,record.type)"
    >
      <a href="javascript:;">Delete &nbsp&nbsp</a>
    </a-popconfirm>
    <a @click="clickRename(record.id,record.type,record.name)" > &nbsp&nbspRename</a>
  </template>
  
  </a-table>

  <!-- 新建文件夹弹窗表单 -->
    <a-modal
      title="新建文件夹"
      :visible="folderVisible"
      :confirm-loading="confirmLoading"
      @ok="handleSubmit"
      @cancel="handleCancelFolder"
    >
      <a-form-model :form="folderForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-form-model-item label="文件夹名">
          <a-input
            v-model="folderForm.name"
            placeholder="请输入文件夹名"
          />
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-input
            v-model="folderForm.remark"
            placeholder="请输入备注"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 文件重命名弹窗 -->
    <a-modal
      title="重命名文件"
      :visible="renameFileVisible"
      :confirm-loading="confirmLoadingRename"
      @ok="handleSubmitRename"
      @cancel="handleCancelRename"
    >
      <a-form-model :form="renameForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-form-model-item label="重命名">
          <a-input
            v-model="renameForm.name"
            placeholder="请输入文件名"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 上传文件夹弹窗 -->
    <a-modal
      title="上传文件"
      :visible="fileVisible"
      :confirm-loading="uploadconfirmLoading"
      @ok="handleUpload"
      @cancel="handleCancelupload"
      
    >

      <a-upload-dragger
        name="file"
        :multiple="false"
         action="http://localhost:8080/jeecg-boot/rsfile/rsFile/add"
        method="post"
        :data="uploadData"
         :headers="uphearder"
        :remove="handleRemove"
        @change="handleChange"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">
          点击或拖拽文件上传
        </p>
        <p class="ant-upload-hint">
          暂仅支持单个文件上传
        </p>
      </a-upload-dragger>

    </a-modal>
</div>
</template>
<script>


import { axios } from '@/utils/request'
import floderImg from '@/assets/fileimage/folder.png'
import filePdf from '@/assets/fileimage/pdf.png'
import mp4 from '@/assets/fileimage/mp4.png'
import fileImg from '@/assets/fileimage/file.png'
export default {
  data() {
    return {
    fileList : [],
      uphearder:{
          'tenant-id': JSON.parse(localStorage.getItem("pro__TENANT_ID")).value
        },
      columns :[
  {
    slots: { title: 'customTitle' },
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '文件大小',
    dataIndex: 'size',
  },
  {
    title: '文件类型',
    dataIndex: 'type',
  },
  {
    title: '创建者',
    dataIndex: 'userName',
  },
  {
    title: '上传日期',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' },
  },
],
    //当前文件夹id
    fileid:0,
    //父文件夹id
    filepid:[],
    //新建文件夹弹窗是否显示
    folderVisible:false,
    folderForm:{
      name:'',
      remark:''
    },
    //新建文件夹确认时加载

    confirmLoading: false,
    //判断是否时新建文件夹时加载文件列表信息(true代表不是)
    isCreateFile: true,
    //判断是否是返回上一层文件列表信息(true代表不是)
    isReback: true,
    //重命名弹窗是否可见
    renameFileVisible: false,
    //重命名弹窗确认加载
    confirmLoadingRename: false,
    //重命名表单
    renameForm:{
      name:''
    },
    //重命名文件的id
    fileId:null,
    //上传文件弹窗是否可见
    fileVisible:false,
    //上传文件确认加载
    uploadconfirmLoading:false,
    //上传的文件
    uploadFileList:[],
    uploadData:{}
    };
  },
  methods:{
    //获取文件信息列表
    getList(id){
      const _this = this
        axios({
            url:'/rsfile/rsFile/filelist',
            method:'get',
            params:{"id":id},
        }).then(function(res){
          if(res.success){
            if(_this.isCreateFile){
              if(_this.isReback){
                _this.filepid.push(_this.fileid)
              }
              console.log(_this.filepid) 
              _this.fileid = id
              _this.isReback=true
            }
            _this.isCreateFile=true

            _this.fileList =  res.result.map( (item,index ) => {
              return {
                ...item,
                key: index,
              }
            })
          }else{
            _this.$message.error('系统异常');
          }
        })
      //axios.get('/rsfile/rsFile/filelist?id='+id).th
    },
    //选择文件图标
    chooseIcon(fileType,filePath){
      if(fileType=="folder"){
        return floderImg
      }else if(fileType=="application/pdf"){
        return filePdf
      }else if(fileType=="image/png"||fileType=="image/jpg"){
        return filePath
      }else if(fileType=="video/mp4"){
        return mp4
      }else{
        return fileImg
      }
    },
    //预览文件
    fileDetail(fileType,filePath,id){
      if(fileType=="folder"){
        this.getList(id)
      } else{
        window.open(filePath, '_blank')
      }
    },
    //回退上级文件夹
    reback(){
      if(this.filepid.length==1){
          this.$message.info('已是最高级文件夹');
      }else{
        const filepid = this.filepid.pop()
        this.isReback=false
        this.getList(filepid)

      }
    },
    //新建文件夹
    createFolder(){
      
    },

    //新建文件夹弹窗确认
    handleSubmit(e){
      this.confirmLoading=true
      const _this = this
      const userInfo = JSON.parse(window.localStorage.getItem("pro__Login_Userinfo"))

      axios({
        url:'/rsfolder/rsFolder/add',
        method:'post',
        params:{
          name:_this.folderForm.name,
          pid:_this.fileid,
          userId:userInfo.value.id,
          remark:_this.folderForm.remark
        }
      }).then(function(res){
        if(res.success){
          _this.isCreateFile=false
          _this.getList(_this.fileid)
          _this.confirmLoading=false
          _this.folderForm.name=''
          _this.folderForm.remark=''
          _this.folderVisible=false
          _this.$message.success('新建成功')
        }else{
          _this.$message.error('新建失败');
        }
      })
    },
    //新建文件夹弹窗取消
    handleCancelFolder(e){
      this.folderForm.name=''
      this.folderForm.remark=''
      this.folderVisible=false
    },
    //删除文件
    onDeleteFile(id,type){
      const _this = this
      if(type=="folder"){
        axios({
          url:'/rsfolder/rsFolder/delete',
          method:'delete',
          params:{"id":id}
        }).then(function(res){
          if(res.success){
            _this.getList(_this.fileid)
            _this.$message.success('删除成功')
          }else{
            _this.$message.error('删除失败');
          }
        })
      }else{
        axios({
          url:'/rsfile/rsFile/delete',
          method:'delete',
          params:{"id":id}
        }).then(function(res){
          if(res.success){
            _this.getList(_this.fileid)
            _this.$message.success('删除成功')
          }else{
            _this.$message.error('删除失败');
          }
        })
      }
      
    },
    //点击重命名
    clickRename(fileId,fileType,fileName){
      if(fileType=="folder"){
        this.$message.warning('文件夹暂不支持重命名')
      }else{
        this.renameForm.name = fileName.slice(0,fileName.lastIndexOf('.'))
        this.fileId = fileId
        this.renameFileVisible = true
      }
      
    },
    //取消重命名弹窗
    handleCancelRename(){
      this.renameForm.name=''
      this.renameFileVisible=false
    },
    //重命名提交
    handleSubmitRename(){
      this.confirmLoadingRename = true
      const _this = this

      axios({
        url:'/rsfile/rsFile/rename',
        method:'put',
        params:{
          name:_this.renameForm.name,
          id:_this.fileId
        }
      }).then(function(res){
        if(res.success){
          _this.isCreateFile=false
          _this.getList(_this.fileid)
          _this.confirmLoadingRename = false
          _this.renameForm.name=''
          _this.renameFileVisible=false
          _this.$message.success('重命名成功')
        }else{
          this.$message.warning('重命名失败')
        }
      })

    },
    //上传文件的删除
    handleRemove(file) {
      const index = this.uploadFileList.indexOf(file);
      const newFileList = this.uploadFileList.slice();
      newFileList.splice(index, 1);
      this.uploadFileList = newFileList;
    },
    //上传文件弹窗取消
    handleCancelupload(){
      this.uploadFileList = []
      this.fileVisible=false
    },
    //beforeUpload 返回 false 后，手动上传文件。
    beforeUpload(file) {
      console.log("进来了1")
      console.log(file)
      this.uploadFileList = [...this.uploadFileList, file];
      console.log("进来了2")
      console.log(this.uploadFileList)
      return false;
    },
    //上传文件确认按钮
    handleUpload(){
      // this.uploadconfirmLoading = true
      // const _this = this
      // const userInfo = JSON.parse(window.localStorage.getItem("pro__Login_Userinfo"))
      // console.log("确认按钮")
      // console.log(_this.uploadFileList)
      // _this.uploadFileList.forEach(file => {
      //   console.log("进来了")
      //   console.log(file)
      //   axios({
      //     url:'/rsfile/rsFile/add',
      //     method:'post',
      //     headers: { 'content-type': 'multipart/form-data' },
      //     //  transformRequest: [function(data, headers) {
      //     // // 去除post请求默认的Content-Type
      //     //   delete headers.post['Content-Type']
      //     //   return data
      //     // }],
      //     data:{
      //       "file":file,
      //       "folderId":_this.fileid,
      //       "userId":userInfo.value.id,
      //       "remark":"上传文件"
      //     }
      //   }).then(function(res){
      //     if(res.success){
      //       _this.isCreateFile=false
      //       _this.getList(_this.fileid)
      //       _this.confirmLoading=false
      //       _this.newFileList=[]
      //       _this.fileVisible=false
      //       _this.$message.success('上传成功')
      //     }else{
      //       _this.$message.error('上传失败');
      //     }
      //   })
      // });
      this.fileVisible=false
    },
    //点击上传
    clickUpload(){
      this.fileVisible=true
      this.uploadData={
        "folderId":this.fileid,
        "userId":JSON.parse(window.localStorage.getItem("pro__Login_Userinfo")).value.id,
        "remark":"上传文件",
        tenantId: JSON.parse(localStorage.getItem("pro__TENANT_ID")).value ? JSON.parse(localStorage.getItem("pro__TENANT_ID")).value : 1
      }
      console.log(this.uploadData)
    },
    //上传状态
    handleChange(info) {
      const status = info.file.status;
      if (status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (status === 'done') {
        this.fileVisible=false
        this.isCreateFile=false
        this.getList(this.fileid)
        info.fileList=[]
        this.$message.success(`${info.file.name} 上传成功.`);
      } else if (status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`);
      }
    },
  },
  created() {
    this.getList(0);
  },
};
</script>
</style>